package com.neusoft.hifly.push.email.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.hifly.commons.exception.SystemErrorException;
import com.neusoft.hifly.core.log.Log;
import com.neusoft.hifly.push.email.config.EmailConfig;
import com.neusoft.hifly.push.email.pojo.MailObj;
import com.neusoft.hifly.push.email.pojo.MailSenderInfo;
import com.neusoft.hifly.push.email.service.IEmailService;
import com.neusoft.hifly.push.email.utils.MailSender;

/**
 * Title: 核心类库
 * <p>
 * Description: 发送邮件
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
@Service("emailService")
public class EmailServiceImpl implements IEmailService {

	@Autowired(required = false)
	private EmailConfig emailConfig;

	/**
	 * 邮件发送
	 *
	 * @param obj
	 *            邮件对象
	 * @throws SystemErrorException
	 *             Excetion
	 */
	@Override
	public void sendMail(final MailObj obj) throws SystemErrorException {
		if (obj == null) {
			return;
		}

		if (!emailConfig.isUse()) {
			Log.error("系统配置禁止使用Email，需要修改config.properties配置文件！");
			return;
		}

		final String smtp = emailConfig.getSmtp();
		// final String pop3 = emailConfig.getPop3();
		final int port = emailConfig.getPort();
		final String sender = emailConfig.getSender();
		final String pwd = emailConfig.getPwd();
		final boolean auth = emailConfig.isAuth();
		final boolean debug = emailConfig.isDebug();

		// 这个类主要是设置邮件
		final MailSenderInfo mailInfo = new MailSenderInfo();
		mailInfo.setHost(smtp);
		mailInfo.setPort(port);
		mailInfo.setUserName(sender);
		mailInfo.setPassword(pwd);
		// 这里没有用户的邮箱密码，所以无法进行身份认证
		mailInfo.setValidate(auth);
		mailInfo.setFromAddress(sender);
		mailInfo.setToAddress(obj.getEmail());
		mailInfo.setSubject(obj.getTitle());
		mailInfo.setContent(obj.getContent());
		mailInfo.setDebug(debug);
		// 这个类主要来发送邮件
		// SimpleMailSender.execute(mailInfo); 不打异常
		final MailSender sms = new MailSender(mailInfo);
		sms.sendMail(mailInfo);
	}

}
